package com.mini.common.util;

import com.google.crypto.tink.Aead;
import com.google.crypto.tink.KeyTemplate;
import com.google.crypto.tink.KeysetHandle;
import com.google.crypto.tink.aead.AeadConfig;
import com.google.crypto.tink.aead.AesGcmKeyManager;
import com.google.crypto.tink.config.TinkConfig;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Base64;

/**
 * @author 小鱼儿
 * @date 2020/11/16 14:33
 */
public class TinkUtil {
    static Aead aesAead = null;
    static byte[] AES_key_array = "qwert@98765@".getBytes();

    public static void init(){
        try {
            TinkConfig.register();
            AeadConfig.register();
            KeysetHandle keysetHandle = KeysetHandle.generateNew(
                    AesGcmKeyManager.aes256GcmTemplate());
            aesAead = keysetHandle.getPrimitive(Aead.class);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
    }


    private static byte[] aesencode(byte[] array) throws GeneralSecurityException {
        return aesAead.encrypt(array, null);
    }

    private static byte[] aesdecode(byte[] array) throws GeneralSecurityException {
        return aesAead.decrypt(array, null);
    }

    public static String encodeBase64AES(String str) throws GeneralSecurityException {
        return Base64.getEncoder().encodeToString(aesencode(str.getBytes()));
    }

    public static byte[] encodeBase64AES(byte[] array) throws GeneralSecurityException {
        return Base64.getEncoder().encode(aesencode(array));
    }

    public static byte[] decodeBase64AES(String str) throws GeneralSecurityException {
        return aesdecode(Base64.getDecoder().decode(str));
    }

    public static byte[] decodeBase64AES(byte[] array) throws GeneralSecurityException {
        return aesdecode(Base64.getDecoder().decode(array));
    }


    public static void main(String[] args) throws GeneralSecurityException, UnsupportedEncodingException {
        TinkUtil.init();
        byte[] qqq = "{\"code\":0,\"msg\":null,\"data\":null}".getBytes();
        qqq = encodeBase64AES(qqq);
        System.out.println(new String(qqq));
        byte[] arrayxx = decodeBase64AES(qqq);
        System.out.println("????:"+new String(arrayxx));
    }
}
